<script setup lang="ts">
import { Rules } from "async-validator";
import { provide, ref } from "vue";
import { FormItem, key } from "./type";
import mitter from "../../utils/mitter";

defineOptions({ name: "ElForm" });

const props = defineProps<{
  model: Record<string, any>;
  rules?: Record<string, Rules>;
}>();

provide(key, {
  model: props.model,
  rules: props.rules,
});

const formItemArr = ref<FormItem[]>([]);

mitter.on("addFormItem", (o: FormItem) => {
  formItemArr.value.push(o);
});

const validate = (cb: (isValidate: boolean) => void) => {
  const task = formItemArr.value.map((item) => item.validator());
  Promise.all(task).then(() => {
    cb(true);
  }).catch(() => {
    cb(false);
  });
};

defineExpose({ validate });
</script>

<template>
  <div class="el-form">
    <slot></slot>
  </div>
</template>
